<template>
  <!-- 预约次数排行 -->
  <div class="chart-box2">
    <div class="chart-title w-100p">预约次数排行</div>
    <div class="chart-content">
      <div class="chart-container" :id="chartId"></div>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  onBeforeUnmount,
  nextTick,
  watch,
} from "vue";
import { Chart, registerTheme } from "@antv/g2";
import common from "../../utils/common";
import store from "../../../../store";

export default defineComponent({
  user_name: "MeetingRoomOrderTimesRank",
  setup() {
    const state = reactive({
      chartId: "meetingRoomOrderTimesRankChart",
      chart: null,
      data: [],
    });

    const initChart = () => {
      const data = state.data;

      state.chart = new Chart({
        container: state.chartId,
        autoFit: true,
        theme: "chartTheme",
      });

      state.chart.data(data);
      state.chart.scale("book_count", { nice: true, alias: "预约次数" });
      state.chart.coordinate().transpose();
      state.chart.tooltip({
        showMarkers: false,
      });
      state.chart.interaction("active-region");
      state.chart.interval().position("user_name*book_count");

      state.chart.render();
    };

    watch(
      () => store.getters.centerControl.MeetingRoom_bookNumRank,
      (val) => {
        if (val) {
          getData();
        }
      }
    );

    const getData = () => {
      const { MeetingRoom_bookNumRank } = store.getters.centerControl;
      if (MeetingRoom_bookNumRank) {
        state.data = MeetingRoom_bookNumRank.reverse();
        if (state.chart) {
          state.chart.changeData(state.data);
        } else {
          nextTick(() => {
            initChart();
          });
        }
      }
    };

    onMounted(() => {
      registerTheme("chartTheme", common.chartTheme);
      getData();
    });

    onBeforeUnmount(() => {
      const chartBox = document.getElementById(state.chartId);
      if (chartBox) {
        chartBox.innerHTML = "";
      }
    });
    return {
      ...toRefs(state),
    };
  },
});
</script>

<style lang="less" scoped>
@import "../../styles/common.less";
</style>
